package com.caltco.cargo.ops.common.base;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper;
import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.caltco.cargo.ops.common.utils.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;

/**
* @Description:    自定义LambdaQueryWrapper
* @Author:         yehao
* @CreateDate:     2022/12/8 15:26
* @UpdateUser:     yehao
* @UpdateDate:     2022/12/8 15:26
* @UpdateRemark:   修改内容
* @Version:        1.0
*/

public class PermissionLambdaQueryWrapper<T> extends AbstractLambdaWrapper<T, PermissionLambdaQueryWrapper<T>>
        implements Query<PermissionLambdaQueryWrapper<T>, T, SFunction<T, ?>> {

    private SelectBuilder sqlSelect = new SelectBuilder();


    /**
     * 不建议直接 new 该实例，使用 Wrappers.lambdaQuery(entity)
     */
    public PermissionLambdaQueryWrapper(BasicPageParams params) {
        super.initNeed();
        if (ObjectUtil.isNotNull(params.getParams().get("dataScope"))){
            this.apply("1=1" + params.getParams().get("dataScope").toString());
        }
    }


    /**
     * 不建议直接 new 该实例，使用 Wrappers.lambdaQuery(...)
     */
    PermissionLambdaQueryWrapper(T entity, Class<T> entityClass, SelectBuilder sqlSelect, AtomicInteger paramNameSeq,
                                 Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments,
                                 SharedString lastSql, SharedString sqlComment, SharedString sqlFirst) {
        super.setEntity(entity);
        super.setEntityClass(entityClass);
        this.paramNameSeq = paramNameSeq;
        this.paramNameValuePairs = paramNameValuePairs;
        this.expression = mergeSegments;
        this.sqlSelect = sqlSelect;
        this.lastSql = lastSql;
        this.sqlComment = sqlComment;
        this.sqlFirst = sqlFirst;
    }

    /**
     * SELECT 部分 SQL 设置
     *
     * @param columns 查询字段
     */
    @Override
    @SafeVarargs
    public final PermissionLambdaQueryWrapper<T> select(SFunction<T, ?>... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {
            this.sqlSelect.getParts().add(columnsToString(columns));
        }
        return typedThis;
    }

    /**
     * 过滤查询的字段信息(主键除外!)
     * <p>例1: 只要 java 字段名以 "test" 开头的             -> select(i -&gt; i.getProperty().startsWith("test"))</p>
     * <p>例2: 只要 java 字段属性是 CharSequence 类型的     -> select(TableFieldInfo::isCharSequence)</p>
     * <p>例3: 只要 java 字段没有填充策略的                 -> select(i -&gt; i.getFieldFill() == FieldFill.DEFAULT)</p>
     * <p>例4: 要全部字段                                   -> select(i -&gt; true)</p>
     * <p>例5: 只要主键字段                                 -> select(i -&gt; false)</p>
     *
     * @param predicate 过滤方式
     * @return this
     */
    @Override
    public PermissionLambdaQueryWrapper<T> select(Class<T> entityClass, Predicate<TableFieldInfo> predicate) {
        if (entityClass == null) {
            entityClass = getEntityClass();
        } else {
            setEntityClass(entityClass);
        }
        Assert.notNull(entityClass, "entityClass can not be null");
        this.sqlSelect.getParts().add(TableInfoHelper.getTableInfo(entityClass).chooseSelect(predicate));
        return typedThis;
    }

    @Override
    public String getSqlSelect() {
        return sqlSelect.getStringValue();
    }

    /**
     * 用于生成嵌套 sql
     * <p>故 sqlSelect 不向下传递</p>
     */
    @Override
    protected PermissionLambdaQueryWrapper<T> instance() {
        return new PermissionLambdaQueryWrapper<>(getEntity(), getEntityClass(), null, paramNameSeq, paramNameValuePairs,
                new MergeSegments(), SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString());
    }

    @Override
    public void clear() {
        super.clear();
        sqlSelect.toNull();
    }

// =================== 上面的代码都是照抄的   =====================

    public PermissionLambdaQueryWrapper<T> min(SFunction<T, ?> column){
        if (column != null) {
            this.sqlSelect.getParts().add(String.format("min(%s)", columnToString(column)));
        }
        return typedThis;
    }

    public PermissionLambdaQueryWrapper<T> max(SFunction<T, ?> column){
        if (column != null) {
            this.sqlSelect.getParts().add(String.format("max(%s)", columnToString(column)));
        }
        return typedThis;
    }

    public PermissionLambdaQueryWrapper<T> sum(SFunction<T, ?> column){
        if (column != null) {
            this.sqlSelect.getParts().add(String.format("sum(%s)", columnToString(column)));
        }
        return typedThis;
    }

    public PermissionLambdaQueryWrapper<T> as(String asName){
        if (StringUtils.isEmpty(asName)) {
            return typedThis;
        }

        List<String> parts = this.sqlSelect.getParts();

        if (CollectionUtil.isEmpty(parts)) {
            return typedThis;
        }

        String lastPart = parts.remove(parts.size() - 1);
        lastPart += " as " + asName;

        parts.add(lastPart);


        return typedThis;
    }

//    public MyLambdaQueryWrapper<T> dataScope(BasicPageParams params) {
//        this.apply("1=1" + params.getParams().get("dataScope").toString());
//        return typedThis;
//    }
}

